<template>
  <div v-if="details.goods_id" class="goods-detail">
    <!-- 商品图片轮播 -->
    <!-- <el-carousel height="400px" v-if="details.img_urls && details.img_urls.length > 0">
      <el-carousel-item v-for="(img, index) in details.img_urls" :key="index">
        <img :src="img" alt="商品图片" class="carousel-img" />
      </el-carousel-item>
    </el-carousel> -->
    <!-- 修改轮播图部分 -->
    <el-carousel height="60vh" :autoplay="false">
      <el-carousel-item v-for="(img, index) in details.img_urls" :key="index"
        style="display: flex; justify-content: center; align-items: center">
        <img :src="img" alt="商品图片" class="carousel-img"
          style="max-width: 100%; max-height: 100%; object-fit: contain" />
      </el-carousel-item>
    </el-carousel>

    <!-- 商品信息 -->
    <div class="goods-info">
      <h1 class="goods-name">{{ details.goods_name }}</h1>
      <p class="goods-desc">{{ details.goods_desc }}</p>
      <div class="price-section">
        <span class="price">¥{{ details.goods_price.toFixed(2) }}</span>
      </div>
      <div class="stock">库存: {{ details.goods_stock }}</div>
      <div class="detail">成色: {{ details.goods_detail }}成新</div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="addToCart">加入购物车</el-button>
        <el-button type="success" @click="buyNow">立即购买</el-button>
      </div>
    </div>
  </div>
  <div v-else>
    <el-skeleton :rows="5" animated />
  </div>
</template>

<script>
import axios from "../../api/axios.config";
import { useUserStore } from "@/stores/user";
import { mapStores } from "pinia";
export default {
  computed: {
    ...mapStores(useUserStore),
  },
  data() {
    return {
      details: {},
    };
  },

  methods: {
    loadDetails() {
      this.details = JSON.parse(sessionStorage.getItem("currentGoods")) || {};
      console.log("###########");
      console.log(this.details.goods_name);
      console.log("###########");
    },

    // 加入购物车
    async addToCart() {
      const currentGoods = JSON.parse(sessionStorage.getItem("currentGoods"));

      if (!currentGoods) {
        this.$message.error("无法获取商品信息");
        return;
      }

      const goodsId = currentGoods.goods_id;
      const userId = this.userStore.studentId;
      console.log('商品id', goodsId);
      if (!userId) {
        this.$message.error("请先登录");
        return;
      }

      try {
        const res = await axios.post("/carts/add", {
          user_id: userId,
          product_id: goodsId,
        });

        if (res.data.code === 200) {
          this.$message.success("已加入购物车");
        } else {
          this.$message.error(res.data.message || "加入购物车失败");
        }
      } catch (err) {
        console.error(err);
        this.$message.error("网络错误，请稍后再试");
      }
    },

    // 立即购买
    async buyNow() {
      const currentGoods = JSON.parse(sessionStorage.getItem("currentGoods"));

      if (!currentGoods) {
        this.$message.error("无法获取商品信息");
        return;
      }

      const goodsId = currentGoods.goods_id;
      const userId = this.userStore.studentId;

      if (!userId) {
        this.$message.error("请先登录");
        return;
      }

      try {
        // 提交订单
        const orderResponse = await axios.post('orders/buynow/', {
          buyer_id: userId,
          item_id: goodsId
        });

        const orderId = orderResponse.data.data.orders;

        if (!orderId) {
          this.$message.error("订单创建失败");
          return;
        }

        // ✅ 简单的消息提示
        this.$message.success("订单提交成功，请完成支付");

        // 支付请求
        const payResponse = await axios.post('/orders/pay', {
          orderIds: [orderId],
          amount: currentGoods.goods_price
        });

        const paymentUrl = payResponse.data.data.paymentUrl;

        if (paymentUrl) {
          window.location.href = paymentUrl; // 跳转到支付页面
        } else {
          this.$message.error('支付链接为空，请重试');
        }

      } catch (error) {
        console.error("提交订单或支付失败:", error);
        this.$message.error("操作失败，请重试");
      }
    }
  },

  mounted() {
    this.loadDetails();
  },
};
</script>

<style scoped>
.goods-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* .el-carousel {
  margin-bottom: 20px;
}

.carousel-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
} */

/* 修改轮播图容器样式 */
.el-carousel {
  width: 100%;
  margin: 0 auto;
  background: #f5f5f5;
  /* 添加背景色处理留白 */
}

/* 修改图片样式 */
.carousel-img {
  width: auto !important;
  /* 取消固定宽度 */
  height: auto !important;
  /* 取消固定高度 */
  max-width: 100%;
  /* 限制最大宽度 */
  max-height: 60vh;
  /* 与轮播图高度一致 */
  object-fit: contain;
  /* 完整显示不裁剪 */
  object-position: center;
  /* 确保居中显示 */
}

.goods-info {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.goods-name {
  font-size: 24px;
  margin-bottom: 10px;
}

.goods-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.price-section {
  margin-bottom: 10px;
}

.price {
  font-size: 24px;
  color: #ff4d4f;
  font-weight: bold;
}

.stock,
.detail {
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
}

.action-buttons {
  margin-top: 20px;
}

.action-buttons .el-button {
  margin-right: 10px;
}
</style>
